package com.ugold.common.util.string;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author zhangweijie
 * @Date 2019/7/3 0003
 * @time 上午 11:50
 **/
public class StringUtils {

    /**
     * 反转List组装成字符串
     * @param list
     * @param divider 分隔符
     * @return
     */
    public static String reverseList(List<String> list, String divider) {
        StringBuffer stringBuffer = new StringBuffer();
        int startPos = list.size() - 1;
        for (int i = startPos; i >= 0; i--) {
            if (divider != null && i != startPos) {
                stringBuffer.append(divider);
            }
            stringBuffer.append(list.get(i));
        }
        return stringBuffer.toString();
    }

    /**
     * 是否包含汉字
     */
    public static boolean containsHanScript(String s) {
        if(s == null || s.length() == 0){
            return false;
        }

        return s.codePoints().anyMatch(
                codePoint ->
                        Character.UnicodeScript.of(codePoint) == Character.UnicodeScript.HAN);
    }

    /**
     * 提取汉字(只提取第一组汉字)
     */
    public static String getFirstHanGroup(String s) {
        if(s == null || s.length() == 0){
            return "";
        }

        String regex="([\u4e00-\u9fa5]+)";
        Matcher matcher = Pattern.compile(regex).matcher(s);
        if(matcher.find()){
            return matcher.group(0);
        }
        return "";
    }

    public static boolean isNull(String str) {
        return str == null || str.length() == 0 || str.equals("null") || str.equals("NULL");
    }

    /**
     * 去除重复字符串
     * @param params  字符串
     * @return divider 分隔符
     */
    public static String removeSameString(String params, String divider){
        if (org.apache.commons.lang3.StringUtils.isBlank(divider))
            divider = ",";

        Set<String> mlinkedset = new LinkedHashSet<>();
        String[] strArray = params.split(divider);
        for (String str : strArray){
            mlinkedset.add(str);
        }
        return String.join(divider,mlinkedset);
    }

   /**
     * 将空字符转为""，保证返回字符不为空
     * @param str
     * @return
     */
    public static String null2String(Object str) {
        return str == null ? "" : str.toString();
    }

    /**
     * 生成uuid
     * @return
     */
    public static String generateUUID(){
        return UUID.randomUUID().toString().replace("-", "");
    }
}
